//
// Created by yyl on 2018/6/6.
//

#include "YQueue.h"

YQueue::YQueue(PlayStatus *playStatus) {
    this->playStatus = playStatus;
    pthread_mutex_init(&mutexPacket, NULL);
    pthread_cond_init(&condPacket, NULL);
}

YQueue::~YQueue() {
    clearAvPacket();
    pthread_mutex_destroy(&mutexPacket);
    pthread_cond_destroy(&condPacket);
}

int YQueue::putAvpacket(AVPacket *packet) {
    pthread_mutex_lock(&mutexPacket);
    queuePacket.push(packet);
//    LOGI("");
    pthread_cond_signal(&condPacket);
    pthread_mutex_unlock(&mutexPacket);

    return 0;
}

int YQueue::getAvpacket(AVPacket *packet) {
    pthread_mutex_lock(&mutexPacket);
    while (playStatus != NULL && !playStatus->exit) {
        if (!queuePacket.empty()) {
            AVPacket *avPacket = queuePacket.front();
            if (av_packet_ref(packet, avPacket) == 0) {//给一个新的引用地址或者内存拷贝新的包给packet
                queuePacket.pop();
            }
            av_packet_free(&avPacket);//这里只会释放avPacket *data 以外的引用 因为 *data 被另一个 packet 引用了
            av_free(avPacket);
            avPacket = NULL;
            //     LOGI("队列里还剩avPacket  size=%d", queuePacket.size());
            break;
        } else {
            pthread_cond_wait(&condPacket, &mutexPacket);
        }
    }
    pthread_mutex_unlock(&mutexPacket);
    if (playStatus == NULL || playStatus->exit) {
        return -1;
    }
    return 0;
}

int YQueue::getQueueSize() {
    int size = 0;
    pthread_mutex_lock(&mutexPacket);
    size = queuePacket.size();
    pthread_mutex_unlock(&mutexPacket);
    return size;
}

void YQueue::clearAvPacket() {
    pthread_cond_signal(&condPacket);
    pthread_mutex_lock(&mutexPacket);
    while (!queuePacket.empty()) {
        AVPacket *avPacket = queuePacket.front();
        queuePacket.pop();
        av_packet_free(&avPacket);//这里只会释放avPacket *data 以外的引用 因为 *data 被另一个 packet 引用了
        av_free(avPacket);
        avPacket = NULL;
    }
    pthread_mutex_unlock(&mutexPacket);
}

void YQueue::release() {
    pthread_cond_signal(&condPacket);
}




